package com.bfly.mall.system.api;

import com.bfly.common.ResponseUtil;
import com.bfly.common.util.DataConvertUtils;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.cache.CityCacheUtil;
import com.bfly.core.context.event.CityReloadEvent;
import com.bfly.mall.system.entity.City;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 城市Api Controller
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/10/10 17:52
 */
@RestController
@RequestMapping(value = "/api/city")
public class CityApiController extends BaseController {

    /**
     * 全国省份列表
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/10/10 17:55
     */
    @GetMapping(value = "/list")
    public void listCity(HttpServletRequest request, HttpServletResponse response) {
        String levelStr = request.getParameter("level");
        int level = DataConvertUtils.convertToInteger(levelStr);
        List<City> cities = CityCacheUtil.getData(level);
        if (CollectionUtils.isEmpty(cities)) {
            // 如果缓存数据没有则触发重新加载数据事件
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            ctx.publishEvent(new CityReloadEvent(ctx));
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(cities));
    }
}
